package com.hskn.hss.module.tlthreshold.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.tlthreshold.entity.TlThreshold;
import com.hskn.hss.module.tlthreshold.mapper.TlThresholdMapper;
import com.hskn.hss.module.tlthreshold.service.ITlThresholdService;
import com.hskn.hss.module.tlthresholdtrans.service.ITlThresholdTransService;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.redis.RedisUtil;
import com.hskn.hss.utils.redis.key.CarAlarmMultiKey;
import com.hskn.hss.utils.redis.key.CarAlarmOneKey;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-12
 */
@Service
public  class TlThresholdServiceImpl extends ServiceImpl<TlThresholdMapper, TlThreshold> implements ITlThresholdService {

    @Resource
    TlThresholdMapper tlThresholdMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    ITlThresholdTransService tlThresholdTransService;

    @Override
    public AjaxResult insert(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        TlThreshold tlThreshold = params.getObject("data", TlThreshold.class);
//        TlThreshold tlThreshold = JSON.parseObject(params.getJSONObject("data").toJSONString(), TlThreshold.class);

        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, uid);
        String deptid = sysUserDepartMapper.selectOne(queryWrapper).getDepid();

        tlThreshold.setCreateby(uid);
        tlThreshold.setCreatetime(new Date());
        tlThreshold.setDeptid(deptid);
        int i = tlThresholdMapper.insert(tlThreshold);
        boolean flag = i > 0 ? true : false;

        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    public AjaxResult update(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        TlThreshold tlThreshold = params.getObject("data", TlThreshold.class);
        String ids = tlThreshold.getIds();
        String[] itemidArray = null;
        if(StringUtils.isNotEmpty(ids)){
            itemidArray = ids.split(",");

        }

        tlThreshold.setUpdateby(uid);
        tlThreshold.setUpdatetime(new Date());

        int i;
        if (StringUtils.isNotEmpty(tlThreshold.getId())&&StringUtils.isEmpty(tlThreshold.getIds())){
            i = tlThresholdMapper.updateById(tlThreshold);
        } else if(StringUtils.isNotEmpty(tlThreshold.getIds())) {
            List<String> idlist = new ArrayList<>();
            for (String itemid : itemidArray) {
                idlist.add(itemid);
            }
            UpdateWrapper<TlThreshold> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().in(TlThreshold::getItemid, idlist);
            updateWrapper.lambda().eq(TlThreshold::getSysname, tlThreshold.getSysname());
            updateWrapper.lambda().eq(TlThreshold::getAlarmname, tlThreshold.getAlarmname());
            i = tlThresholdMapper.update(tlThreshold,updateWrapper);

        }else{
            TlThreshold tlThreshold2 = new TlThreshold();
            tlThreshold2.setStatus(tlThreshold.getStatus());
            tlThreshold2.setUpdateby(uid);
            tlThreshold2.setUpdatetime(new Date());
            tlThreshold2.setSysname(tlThreshold.getSysname());
            tlThreshold2.setAlarmname(tlThreshold.getAlarmname());
            tlThreshold2.setFaclitypeid(tlThreshold.getFaclitypeid());
            i = tlThresholdMapper.updateTlThreshold(tlThreshold2);
        }

        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    public AjaxResult deletebyid(JSONObject params) throws HssException {
        String id = params.getString("id");
        tlThresholdMapper.deleteById(id);
        return AjaxResult.success("操作成功");
    }

    @Override
    public TlThreshold getDetail(JSONObject params) throws HssException {
        String ids = params.getString("ids");
        if (StringUtils.isNotEmpty(ids)){
            QueryWrapper<TlThreshold> thresholdQueryWrapper=new QueryWrapper<>();
            List<String> ids2= Arrays.asList(ids.split(","));
            thresholdQueryWrapper.lambda().in(TlThreshold::getItemid,ids2);
            String sysname = params.getString("sysname");
            thresholdQueryWrapper.lambda().eq(TlThreshold::getSysname,sysname);
            String alarmname = params.getString("alarmname");
            thresholdQueryWrapper.lambda().eq(TlThreshold::getSysname,alarmname);
            List<TlThreshold> tlThresholds = tlThresholdMapper.selectList(thresholdQueryWrapper);

            Map<String, List<TlThreshold>> tlThresholdsByThreshold = tlThresholds.stream().collect(Collectors.groupingBy(TlThreshold::getThreshold));
            Map<String, List<TlThreshold>> tlThresholdsByStatus = tlThresholds.stream().collect(Collectors.groupingBy(TlThreshold::getStatus));

            TlThreshold tlThreshold = tlThresholds.get(0);
            if (tlThresholdsByThreshold.size() > 1){
                tlThreshold.setThreshold("{}");
            }
            if (tlThresholdsByStatus.size() > 1){
                tlThreshold.setStatus("");
            }
            return tlThreshold;
        } else {
            String id = params.getString("id");
            TlThreshold tlThreshold = tlThresholdMapper.selectById(id);
            return tlThreshold;
        }
    }

    @Override
    public List getSelectList(JSONObject params) {
        Map<String, Object> map = new HashMap();
//        map.put("sysname" , params.getString("sysname")); //阀值类型
//        map.put("alarmname" , params.getString("alarmname")); //大类
        map.put("thresholdtype", params.getString("thresholdtype")); //阀值类型
//        map.put("faclitypeid" , params.getString("faclitypeid")); //大类
//        map.put("itemid" , params.getString("itemid")); //数据id
//        map.put("status" , params.getString("status"));
        List resultList = tlThresholdMapper.getSelectList(map);
        return resultList;
    }

    @Override
    @DataScope(deptAlias = "deptid", userAlias = "createby, updateby")
    public JSONObject getList(BaseEntity entity, JSONObject params) throws HssException {
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        JSONObject json = new JSONObject();

        Map<String, Object> map = new HashMap();
        map.put("sysname", params.getString("sysname")); //阀值类型
        map.put("alarmname", params.getString("alarmname")); //大类
        map.put("thresholdtype", params.getString("thresholdtype")); //阀值类型
        map.put("faclitypeid", params.getString("faclitypeid")); //大类
        map.put("itemid", params.getString("itemid")); //数据id
        map.put("status", params.getString("status"));
        map.put("params", entity.getParams());

        if (StringUtils.isNotEmpty(params.getString("ids"))){
            List<String> list= Arrays.asList(params.getString("ids").split(","));
            String ids = "\"" + StringUtil.join(list.toArray(),"\",\"") + "\"";
            map.put("ids", ids); //数据ids
        }

        Page<TlThreshold> listPage = new Page<>(page, size, true);
        IPage<TlThreshold> iPage = tlThresholdMapper.listTlThreshold(listPage, map);
        List<TlThreshold> thresholdList = iPage.getRecords();
        if (Objects.nonNull(thresholdList) && thresholdList.size()>0){
            for (TlThreshold threshold : thresholdList
                 ) {
                String thresholdStr = threshold.getThreshold();
                String thresholdflag = threshold.getThresholdflag();
                if (StringUtils.isNotEmpty(thresholdflag) && thresholdflag.indexOf(",")>0){
                        String[] thresholdSplit = thresholdflag.split(",");
                    for (String str:thresholdSplit
                         ) {
                        if (!thresholdStr.equals(str)){
                            threshold.setThreshold("{}");
                        }
                    }
                }
                String statusStr = threshold.getStatus();
                String statusStrflag = threshold.getStatusflag();
                if (StringUtils.isNotEmpty(statusStrflag) && statusStrflag.indexOf(",")>0){
                    String[] statusSplit = statusStrflag.split(",");
                    for (String str:statusSplit
                         ) {
                        if (!statusStr.equals(str)){
                            threshold.setStatus("");
                        }
                    }
                }
                if ("0".equals(threshold.getStatus())){
                    threshold.setStatusName("停用");
                } else if ("1".equals(threshold.getStatus())) {
                    threshold.setStatusName("启用");
                } else {
                    threshold.setStatusName("");
                }
                String threshStr = threshold.getThreshold();
                threshold.setThreshold(splitstr(threshStr));
            }
        }

        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("thresholdlist", iPage.getRecords());
        return json;
    }

    public String splitstr(String threshStr) {
        if (threshStr.equals("{}")) {
            return "";
        }
        String str = threshStr.substring(1, threshStr.length() - 1).replace("\"", "");
        String resultStr = "";
        String[] strarrys = str.split(",");
        int i = 0;
        for (String str1 : strarrys) {
            i++;
            String[] strarry2 = str1.split(":");
            resultStr += tlThresholdTransService.getTrans(strarry2[0], strarry2[1]);
            if (strarrys.length != i) {
                resultStr += ",";
            }
        }
        return resultStr;
    }

    @Override
    public TlThreshold getCarOneThresholdFromRedis(String itemId, String alarmNameSearch) {
        try {
            List<JSONObject> listObject = RedisUtil.get(CarAlarmOneKey.token, itemId, List.class);
            if (CollectionUtils.isEmpty(listObject)) {
                QueryWrapper<TlThreshold> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(TlThreshold::getItemid, itemId);
                queryWrapper.lambda().eq(TlThreshold::getStatus, "1");
                List<TlThreshold> tlThresholdList = tlThresholdMapper.selectList(queryWrapper);
                RedisUtil.set(CarAlarmOneKey.token, itemId, tlThresholdList);
                for (TlThreshold tlThreshold : tlThresholdList) {
                    if (alarmNameSearch.equals(tlThreshold.getAlarmname())) {
                        return tlThreshold;
                    }
                }
            } else {
                for (JSONObject jsonObject : listObject) {
                    String alarmname = jsonObject.getString("alarmname");
                    if (alarmNameSearch.equals(alarmname)) {
                        return JSONObject.parseObject(JSONObject.toJSONString(jsonObject), TlThreshold.class);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public List<TlThreshold> getCarThresholdsFromRedis(String itemId) {
        List<TlThreshold> thresholdList = new ArrayList<>();
        try {
            String redisKey = itemId;
//            List<JSONObject> listObject = new ArrayList<>();
            List<JSONObject> listObject = RedisUtil.get(CarAlarmMultiKey.token, redisKey, List.class);
            if (CollectionUtils.isEmpty(listObject)) {
                QueryWrapper<TlThreshold> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(TlThreshold::getItemid, itemId);
                queryWrapper.lambda().eq(TlThreshold::getStatus, "1");
                thresholdList = tlThresholdMapper.selectList(queryWrapper);
                RedisUtil.set(CarAlarmMultiKey.token, redisKey, thresholdList);
            } else {
                for (JSONObject jsonObject : listObject) {
                    thresholdList.add(JSONObject.parseObject(JSONObject.toJSONString(jsonObject), TlThreshold.class));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return thresholdList;
    }

    @Override
    public Map<String, TlThreshold> getThresholdMap(){
        List<TlThreshold> tlThresholdList=tlThresholdMapper.selectList(new QueryWrapper<>());
        Map<String, TlThreshold> departMap= new HashMap<>();
        if (!tlThresholdList.isEmpty()) {
            departMap = GroupingByUtils.getGroupingForMapEntity(tlThresholdList, TlThreshold::getItemid, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        return departMap;
    }

    @Override
    public Map<String, List<TlThreshold>> getThresholdListMap(){
        List<TlThreshold> tlThresholdList=tlThresholdMapper.selectList(new QueryWrapper<>());
        Map<String, List<TlThreshold>> tlThresholdListMap = new HashMap<>();
        if (!tlThresholdList.isEmpty()) {
            tlThresholdListMap = tlThresholdList.stream().filter(tlThreshold -> StringUtils.isNotEmpty(tlThreshold.getItemid())).collect(Collectors.groupingBy(TlThreshold::getItemid));
        }
        return tlThresholdListMap;
    }
}
